package cn.gson.fengboot.model.service;

import cn.gson.fengboot.controller.DbusinessController;
import cn.gson.fengboot.model.LpojosVo.LspVo;
import cn.gson.fengboot.model.dao.*;
import cn.gson.fengboot.model.mapper.DofferMapper;
import cn.gson.fengboot.model.mapper.LshenpiMapper;
import cn.gson.fengboot.model.pojos.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class DofferService {

    @Autowired
    DofferMapper dofferMapper;

    @Autowired
    DofferDao dofferDao;

    @Autowired
    DbusinessDao dbusinessDao;

    @Autowired
    DofferdetailsDao dofferdetailsDao;

    @Autowired
    DphaseDao dphaseDao;
    @Autowired
    DbusinessController controller;

    @Autowired
    LshenpiMapper lshenpiMapper;

    public void addOffer(Doffer doffer) {
        if(doffer.getOfferId()==0){
            doffer.setOfferStatu(1);
            doffer.setOfferAudit("未审核");
            doffer.setOfferAccept("未接受");
        }

        Doffer save = dofferDao.save(doffer);


        Collection<Dofferdetails> offerList = doffer.getOfferList();
        for (Dofferdetails s:offerList){
            s.setOfferId(save);
        }
        dofferdetailsDao.saveAll(offerList);

        if(doffer.getBusiness().getPhase().getPhaseId()==3){
            Dbusiness dbusiness = dbusinessDao.findById(doffer.getBusiness().getBusId()).get();
            Dphase dphase1 = dphaseDao.findById(doffer.getBusiness().getPhase().getPhaseId() + 1).get();
            dbusiness.setBusPossibility(dphase1.getPhasePoss());
            dbusiness.setPhase(dphase1);
        }

        addsp(save);//新增审批

    }


    public void addsp(Doffer save){
        Integer offerId = save.getOfferId();
        QempFrom offerExamine = save.getOfferExamine();
        LspVo lshenpi = new LspVo(offerId,"报价申请",new Date(),save.getOfferPeople(),save.getOfferTheme(),"未审核",offerExamine.getEmpId());
        lshenpiMapper.addlshenpi(lshenpi);;//新增审批
    }

    public List<Doffer> selectOfferBybusId(Integer busId, Integer offerId) {
        return dofferMapper.selectOfferBybusId(busId,offerId);
    }

    public void editofferAccept(Integer offerId) {
        Doffer doffer = dofferDao.findById(offerId).get();
        doffer.setOfferAccept("已接受");
        dofferDao.save(doffer);
    }

    public List<QdepFrom> selectapprove() {
        String approve = "审批";
        return dofferMapper.selectapprove(approve);
    }

    public Doffer verifymyoffersheme(String offerTheme, HttpServletRequest request) {
        String getbuspeople = controller.getbuspeople(request);
        return dofferDao.findByOfferTheme(offerTheme,getbuspeople);
    }
}
